namespace CISLib.Mail
{
    using CISLib;
    using OpenSmtp.Mail;
    using System;

    public sealed class MailHelper
    {
        internal const string MailIDHeader = "X-CIS.MailId";

        public static MailMessage BuildMailMessageEx(MailConfig configer, EmailPool email)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.Charset = "GB2312";
            mailMessage.From = new EmailAddress(MailConfig.SmtpSender);
            SetMailMessageRecipients(mailMessage, email.Recipient, AddressType.To);
            SetMailMessageRecipients(mailMessage, email.Cc, AddressType.Cc);
            SetMailMessageRecipients(mailMessage, email.Bcc, AddressType.Bcc);
            mailMessage.Subject = email.Subject;
            if (email.BodyType == 2)
            {
                mailMessage.HtmlBody = email.Body;
            }
            else
            {
                mailMessage.Body = email.Body;
            }
            mailMessage.Priority = "High";
            mailMessage.Notification = false;
            mailMessage.AddCustomHeader("X-CIS.MailId", email.EmailId.ToString());
            return mailMessage;
        }

        private static bool NotNullAndEmpty(string address)
        {
            return ((address != null) && (address != string.Empty));
        }

        private static void SetMailMessageRecipients(MailMessage mailMessage, string address, AddressType addrType)
        {
            if (NotNullAndEmpty(address))
            {
                foreach (string addr in address.Split(new char[] { ',' }))
                {
                    mailMessage.AddRecipient(new EmailAddress(addr), addrType);
                }
            }
        }
    }
}

